package com.hz.control;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collection;

import com.hz.dbconn.DBConnect;
import com.hz.model.Hobby;

public class HobbyControl {
    
    /*
     * 新增特长
     */
    public static boolean AddHobby(Hobby h) {
	DBConnect dbc = new DBConnect();
	String sql = "insert into hobby (hobbyName)values(?)";
	dbc.prepareStatement(sql);
	try {
	    dbc.setString(1, h.getHobbyName());
	    dbc.executeUpdate();
	    return true;
	} catch (Exception e) {
	    // TODO: handle exception
	    e.printStackTrace();
	    System.out.println("插入失败！");
	    return false;
	}finally{
	    dbc.close();
	}
    }
    //修改
    public static boolean updateHobby(String name,int id) {
	DBConnect dbc = new DBConnect();
	String sql = "update hobby set hobbyName ='"+name+"' where id = '"+id+"'";
	dbc.prepareStatement(sql);
	try {
	    dbc.executeUpdate();
	    return true;
	} catch (Exception e) {
	    // TODO: handle exception
	    e.printStackTrace();
	    System.out.println("修改失败！");
	    return false;
	}finally{
	    dbc.close();
	}
    }
    
    //删除
    public static boolean deleteHobby(int id) {
	DBConnect dbc = new DBConnect();
	String sql = "delete from hobby where id = '"+id+"'";
	dbc.prepareStatement(sql);
	try {
	    dbc.executeUpdate();
	    return true;
	} catch (Exception e) {
	    // TODO: handle exception
	    e.printStackTrace();
	    System.out.println("删除失败！");
	    return false;
	}finally{
	    dbc.close();
	}
    }
    
    /*
     * 获取特长内容
     */
    public static String getHobbyName(int id) {
	String name = "";
	DBConnect dbc = new DBConnect();
	String sql = "select hobbyName from hobby where id='"+id+"'";
	dbc.prepareStatement(sql);
	try {
	    ResultSet rs = dbc.executeQuery();
	    if(rs.next()){
		name = rs.getString("hobbyName");
	    }
	    return name;
	} catch (Exception e) {
	    // TODO: handle exception
	    e.printStackTrace();
	    System.out.println("插入失败！");
	    return name;
	}finally{
	    dbc.close();
	}
    }
   
    
    /*
     * 遍历特长（供查询时选择）
     */
    public static Collection<Hobby> getAllHobbies() {
	DBConnect dbc = new DBConnect();
	Collection<Hobby> hlist = new ArrayList<Hobby>();
	Hobby h = null;
	String sql = "select * from hobby"; 
	dbc.prepareStatement(sql);
	ResultSet rs = null;
	try {
	    rs = dbc.executeQuery();
	    while(rs.next()){
		h = new Hobby();
		h.setId(rs.getInt("id"));
		h.setHobbyName(rs.getString("hobbyName"));
		hlist.add(h);
	    }
	    return hlist;
	} catch (Exception e) {
	    // TODO: handle exception
	    e.printStackTrace();
	    System.out.println("遍历特长失败！");
	    return null;
	}finally{
	    dbc.close();
	}
    }
    

}
